from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from utils.config import config
from qiniu import Auth

router = APIRouter(prefix="/qiniu", tags=["七牛云上传"])

class GetUrlRequest(BaseModel):
    key: str

@router.get("/token")
async def get_qiniu_upload_token():
    """获取七牛云上传token"""
    try:
        token = qiniu_token()
        return {"uptoken": token}
    except ValueError as e:
        raise HTTPException(status_code=500, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"生成七牛云token失败: {str(e)}")


@router.post("/url")
async def get_qiniu_url_endpoint(request: GetUrlRequest):
    """根据文件key获取七牛云访问URL"""
    url = get_qiniu_url(request.key)
    return {"url": url}


def qiniu_token():
    """生成七牛云上传token"""
    # 使用配置文件中的七牛云配置
    access_key = config.QINIU_ACCESS_KEY
    secret_key = config.QINIU_SECRET_KEY
    bucket_name = config.QINIU_BUCKET_NAME

    # 验证配置是否完整
    if not access_key or not secret_key or not bucket_name:
        missing_configs = []
        if not access_key:
            missing_configs.append("QINIU_ACCESS_KEY")
        if not secret_key:
            missing_configs.append("QINIU_SECRET_KEY")
        if not bucket_name:
            missing_configs.append("QINIU_BUCKET_NAME")
        raise ValueError(f"七牛云配置不完整，缺少: {', '.join(missing_configs)}。请在环境变量或.env文件中配置这些参数。")

    # 构建鉴权对象
    q = Auth(access_key, secret_key)

    # 生成上传token，有效期1小时
    token = q.upload_token(bucket_name, key=None, expires=3600)

    return token


def get_qiniu_url(key: str) -> str:
    """根据文件key获取七牛云访问URL"""
    domain = config.QINIU_DOMAIN
    if not domain:
        # 如果没有配置域名，使用默认格式
        return f"https://{config.QINIU_BUCKET_NAME}.qiniucdn.com/{key}"
    return f"https://{domain}/{key}"
